package com.richapp.launcher.serialport.gateway;

import android.util.Log;

import java.io.DataInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.jack.util.hex.HexUtil;
import com.richapp.net.util.HexTool;


public class GatewayReadThread implements Runnable {

	private static final String TAG = GatewayReadThread.class.getName();
	private boolean runFlag = false;
	private GatewayMessageListner serialPortMessgeListner = null;
	private DataInputStream dis = null;
	
	public GatewayReadThread(InputStream ins) {
		dis = new DataInputStream(ins);
	}

	@Override
	public void run() {
		Log.d(TAG, "网关信息读取线程启动");
		ByteBuffer buf = ByteBuffer.allocate(19);
		String headStr;
		while(runFlag){
			try {
				if (dis != null){
					if(dis.available() > 0){
						
						byte head = dis.readByte();
						headStr = HexTool.Byte2Hex(head);
						//OK ERRO BUSY FAIL DATA
						if(!GatewaytConstant.INSTRUCTION_HEAD.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_RESULT_ERRO_E_STR.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_BUSY_B_STR.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_FAIL_F_STR.equals(headStr)){
							
							continue;
						}
						buf.put(head);
						for(int i = 0 ; i < GatewaytConstant.INSTRUCTIOIN_BYTES_LENGTH -1 ;i++){
							buf.put(dis.readByte());
						}

						String hexData = HexTool.ByteArrToHex(buf.array());
						Log.d(TAG, "收到设备上报消息:" + hexData);
						buf.clear();

						ControlInstructionMessage cim = GatewayServer.getInstance().getLastMessage();

						//校验
						if(!GatewaytConstant.INSTRUCTION_RESULT_ERRO_E_STR.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_BUSY_B_STR.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_DO_RESULT_FAIL_F_STR.equals(headStr)
								&& !GatewaytConstant.INSTRUCTION_PROOFREADING_STR.equals(headStr)){

							if(cim != null){
								if(GatewaytConstant.INSTRUCTION_FLAG_ADD_ALL.equals(cim.getInstructionFlag())){
									if(!checkData(hexData,1)){
										Log.d(getClass().getName(),"盲扫校验失败，直接丢弃");
										continue;
									}
								}else{
									if(!HexUtil.checkData16Bit(hexData)){
										Log.d(getClass().getName(),"其他数据验失败，直接丢弃");
										continue;
									}
								}
							}else{
								if(!HexUtil.checkData16Bit(hexData)){
									Log.d(getClass().getName(),"主动上报数据验失败，直接丢弃");
									continue;
								}
							}
						}

						//独立红外学习
						if(cim != null && GatewaytConstant.INSTRUCTION_FLAG_INFRARED_STUDY.equals(cim.getInstructionFlag())){
							cim.setResultData(cim.getResultData()+hexData);

							if(hexData.startsWith("FF02")){
								if(serialPortMessgeListner != null){
									serialPortMessgeListner.messageReceived(hexData);
								}
							}
						}else{
							if(serialPortMessgeListner != null){
								serialPortMessgeListner.messageReceived(hexData);
							}
						}
					}
				}
				Thread.sleep(10);
			} catch (Exception e) {
				e.printStackTrace();
				Log.e(TAG, "串口信息读取错误:" + e.getMessage());
			}
		}
		Log.e(TAG, "串口信息读取线程关闭");
	}

	/**
	 * @param hex
	 * @param checkByteCount
	 * @return
     */
	private boolean checkData(String hex,int checkByteCount){
		boolean flag = false;
		byte[] data = HexUtil.HexToByteArr(hex.substring(0,hex.length()-checkByteCount*2));

		int result = 0;
		for(byte b : data){
			result += (int)b;
		}

		String value = Integer.toHexString(result).toUpperCase();

		if(checkByteCount == 2){
			if (value.length() == 1) {
				value = "000" + value;
			} else if (value.length() == 2) {
				value = "00" + value;
			} else if (value.length() == 3) {
				value = "0" + value;
			} else if (value.length() == 4) {

			}
		}else if(checkByteCount == 1){
			if (value.length() == 1) {
				value = "0" + value;
			} else if (value.length() == 2) {

			}
		}

		if(hex.endsWith(value)){
			flag = true;
		}
		return flag;
	}

	public boolean isRunFlag() {
		return runFlag;
	}

	public void setRunFlag(boolean runFlag) {
		this.runFlag = runFlag;
	}

	public GatewayMessageListner getSerialPortMessgeListner() {
		return serialPortMessgeListner;
	}

	public void setSerialPortMessgeListner(GatewayMessageListner serialPortMessgeListner) {
		this.serialPortMessgeListner = serialPortMessgeListner;
	}
}
